package com.wang.lb.impl;

import com.wang.lb.ILoadBalancer;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Classname MyLB
 * @Description TODO
 * @Date 2024/10/12 10:54
 * @Created by pc
 */
@Component
public class MyLB implements ILoadBalancer {

    // 创建一个院子整形 防止高并发导致线程不安全的问题
    private AtomicInteger atomicInteger = new AtomicInteger(0);
    public final int getAndIncrement() {
        // 当前下标
        int current;
        int next;
        do{
          // 获取当前下标
          current = this.atomicInteger.get();
          next = current >= Integer.MAX_VALUE ? 0 : current + 1;
        }while (!this.atomicInteger.compareAndSet(current,next));
        System.out.println("******第几次访问，次数next : " + next);
        return next;
    }
    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstance) {
        // 判断是否有实体提供服务
        if(serviceInstance.size() <= 0){
            return null;
        }
        // 进行取余操作 获取提供服务的下标
        int index  = getAndIncrement() % serviceInstance.size();
        return serviceInstance.get(index);
    }
}
